var files = [], pname
//选择文件后
$(document).on('change', '#uploadimages', function(){
    var files0 = files
    for(i=0;i<this.files.length;i++){
        if(this.files[i].size>=1024*1024){
            mymessage2('文件大小超出限制','<i class="weui_icon_info weui_icon_msg"></i><br/>文件"'+this.files[i].name+'"大小超过1MB<br/>请自行压缩后再上传')
            files = files0
            // files = []
            return
        }
        files.push(this.files[i])
    }
    var uploader = $('ul.weui_uploader_files')
    uploader.empty()
    for(i=0;i<files.length;i++){  
        var url = URL.createObjectURL(files[i])
        uploader.append('<li class="weui_uploader_file img_wait"'
        +' style="background-image:url('+url+')"></li>')
    }
    refreshcount()
    console.info('change')
})
var isuploadwx = false
//上传键
$('#uploadform').submit(function(e){
    e.preventDefault();
    if(isuploadwx){
        uploadimage(files)        
    }else{
        if(files.length>0){
            upload(0)
        }else{
            if(bugfix){
                bugfix = false;
            }else{
                mymessage2('无法上传', '请先添加上传文件后方可上传')            
            }
        }
    }
})
//上传过程
upload = function(i){
    var formdata = new FormData()
    formdata.append('imgfile', files[i])
    formdata.append('pname', $('#pname').val())
    formdata.append('fwcode', $('input[name=fwcode]').val())
    var status = $('<div class="weui_uploader_status_content">0%</div>')
    var progress = $('<div class="weui_progress" style="margin-top: 79px;">'+
        '<div class="weui_progress_bar">'+
            '<div class="weui_progress_inner_bar" style="width: 0%;"></div>'+
        '</div>'+
    '</div>')
    xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function(){
        if(xhr.readyState==4){
            // status.text('100%')
            if(xhr.responseText=='success'){
                status.html('<i class="weui_icon_success"></i>')
                status.parents('li').removeClass('img_wait')
            }else{
                status.html('<i class="weui_icon_warn"></i>')
                status.parents('li').removeClass('img_wait')                
            }
            refreshcount()
            console.info('ReadyState==4:'+xhr.responseText)
            if(i<files.length-1){
                upload(i+1)
            }else{
                $('#uploadbtn').removeClass('weui_btn_disabled').text('继续上传')
                myloadinghide()
                mymessage2('图片上传成功', '已成功将图片上传到审核中心<i class="weui_icon_success weui_icon_msg"></i><br/>点击确定键返回')
                files = []
            }
        }
    }
    xhr.upload.addEventListener('loadstart', function(e){
        $('li.weui_uploader_file').eq(i).append(status).append(progress).addClass('weui_uploader_status')
        $('#uploadbtn').addClass('weui_btn_disabled')
        myloadingshow('上传图片中...')
        console.info('Starting....')
    }, false);   
    xhr.upload.addEventListener('progress', function(e){
        var percent = Math.ceil((e.loaded/e.total).toFixed(2) * 100)+'%'
        status.text(percent)
        progress.find('.weui_progress_inner_bar').css('width', percent)
        console.info(e.loaded, e.total)
    }, false);
    xhr.upload.addEventListener('load', function(e){
        myloadinghide()
        console.info('Loaded...')
    }, false);        
    xhr.upload.addEventListener('error', function(e){
        status.html('<i class="weui_icon_warn"></i>')
        console.info(e)
    }, false);    
    xhr.open('POST', '?action=sellpostimage')
    xhr.send(formdata)
}
//弹出确定菜单
mymessage2 = function(title, content){
    var dailog = $('#dialog2')
    dailog.find('.weui_dialog_title').text(title)
    dailog.find('.weui_dialog_bd').html(content)
    dailog.find('.weui_btn_dialog').click(function(){
        dailog.hide()
    })
    dailog.show()
}
//弹出确实或取消菜单
mymessage1 = function(title, content, sucfunc){
    var dailog = $('#dialog1')
    dailog.find('.weui_dialog_title').text(title)
    dailog.find('.weui_dialog_bd').html(content)
    dailog.find('.weui_btn_dialog.default').click(function(){
        dailog.hide()
    })
    dailog.find('.weui_btn_dialog.primary').unbind('click').click(sucfunc)        
    dailog.show()
}
//弹出输入菜单
myinputdailog = function(title, content, sucfunc){
    var dailog = $('#dialog1')
    dailog.find('.weui_dialog_title').text(title)
    dailog.find('.weui_dialog_bd').html('<input class="weui_input" type="tel" placeholder="'+content+'">')
    dailog.find('.weui_btn_dialog.default').click(function(){
        dailog.hide()
    })
    dailog.find('.weui_btn_dialog.primary').unbind('click').click(sucfunc)        
    dailog.show()    
}
//img_wait图片点击删除确认
$(document).on('click', '.img_wait', function(){
    var self = $(this)
    deletefunc = function(){
        files.splice(self.index(), 1)
        self.remove()
        $('#dialog1').hide()
        refreshcount()
    }
    mymessage1('删除图片确认', '您确定要取消本张图片的上传?<br/>按确定键确认,按取消键返回', deletefunc)
})
//更新图片数目
refreshcount = function(){
    var total = files.length
    var curent = total - $('.img_wait').length
    $('.weui_cell_ft').text(curent + '/'+ total)
}
//设置disable键无效
$(document).on('click', '.weui_btn_disabled', function(){
    return false;
})
//加载Toast
myloadingshow = function(title){
    var toast = $('#loadingToast')
    toast.find('.weui_toast_content').text(title)
    toast.show()
}
myloadinghide = function(){$('#loadingToast').hide()}


//微信js绑定
var iswxset = false;
if($(document).find('.wx_data').length==1){
    myloadingshow('加载插件中...')
    var wxconfig = {}
    $('.wx_data input').each(function(i, e){
        wxconfig[e.name] = e.value;
    })    
    wxconfig.debug = false; //debug 开关
    wxconfig.jsApiList = [
        'checkJsApi', 'chooseImage', 'uploadImage', 'hideMenuItems', 
        'onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ',
        'onMenuShareWeibo', 'onMenuShareQZone', 'previewImage', 'scanQRCode',
    ];
    wx.config(wxconfig);
    wx.ready(function(){
        wx.checkJsApi({
            jsApiList: ['chooseImage', 'uploadImage', 'scanQRCode'],
            success: function(res){               
                iswxset = true;
                myloadinghide();
                $('#fwscan').removeClass('weui_btn_disabled');
            },
        });
    });    
}
var iswxuploaded = false;
//选择上传图片键绑定#uploadimages
$('#uploadimages').click(function(e){
    if(iswxset){
        // e.preventDefault;//无作用
        isuploadwx = true;
        if(iswxuploaded){
            $('.weui_uploader_status_content .weui_icon_success').each(function(){
                $(this).parents('li').remove()
            })
            iswxuploaded = false;
        }
        chooseimage(addpreimage)
        return false;
    }
    console.info('uploadimagesClick!')
})
//微信选择图片功能  
chooseimage = function(handle){
    // $.mobile.loading('show');
    wx.chooseImage({
        count: 9, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            // items.localId = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片 
            // items.localId = items.localId.concat(res.localIds) //直接添加到原localId中
            handle(res.localIds);
        },
        cancel: function(){
            // $.mobile.loading('hide');
        }
    });
}
//微信图片预览
addpreimage = function(items){
    var $div = $('ul.weui_uploader_files')
    // $div.empty()  //清空已经选图片
    for(i=0;i<items.length;i++){
        $div.append('<li class="weui_uploader_file img_wait"'
        +' style="background-image:url('+items[i]+')"></li>');
        files.push(items[i]);
    }
    refreshcount();
}
//上传图片过程
uploadimage = function(){
    // alert('上传图片item为' + items.localId)
    if(files.length==0){
        if(bugfix){
            bugfix = false;
        }else{
            mymessage2('无法上传', '请先添加上传文件后方可上传')       
        }
        return;}
    var i = 0, length = files.length
    var serverIds = [];
    $('#uploadbtn').addClass('weui_btn_disabled')
    upload = function(){
        var stat = $('<div class="weui_uploader_status_content"><i class="weui_icon_waiting"></i></div>')
        var uploader = $('li.weui_uploader_file').eq(i).append(stat).addClass('weui_uploader_status')
        wx.uploadImage({
            localId: files[i],
            success: function(res){
                stat.html('<i class="weui_icon_success"></i>')
                stat.parents('li').removeClass('img_wait')
                refreshcount()                
                i++;
                serverIds.push(res.serverId);
                if(i<length){
                    upload(); 
                }else{
                    // $.mobile.loading('show');
                    submitpost(serverIds);
                }
            }
        })
    }
    upload();    
}
submitpost = function(imageids){
    iswxuploaded = true;
    files = [];
    myloadingshow('数据处理中...')
    var uploadbtn = $('#uploadbtn').removeClass('weui_btn_disabled')
    var pname = $('#pname').val()
    var fwcode = $('input[name=fwcode]').val()
    $.post('?action=submitpost&pname='+pname+'&fwcode='+fwcode, {imageids: imageids.join(',')}, function(data){
        myloadinghide()
        if(data=='success'){
            mymessage2('图片上传成功', '已成功将图片上传到审核中心<i class="weui_icon_success weui_icon_msg"></i><br/>点击确定键返回')
            uploadbtn.text('继续上传')
        }else{
            mymessage2('未知错误', data)
        }
    })
}

// var images1 = ['http://ss.bdimg.com/static/superman/img/logo/bd_logo1_31bdc765.png',
// 'http://img5.imgtn.bdimg.com/it/u=3750695734,1192334129&fm=21&gp=0.jpg',
// 'http://img5.imgtn.bdimg.com/it/u=3750695734,1192334129&fm=21&gp=0.jpg',
// 'http://img5.imgtn.bdimg.com/it/u=3750695734,1192334129&fm=21&gp=0.jpg',
// 'http://img5.imgtn.bdimg.com/it/u=3750695734,1192334129&fm=21&gp=0.jpg',
// 'http://img0.imgtn.bdimg.com/it/u=751865090,564508156&fm=21&gp=0.jpg']

//获取url变量值
getarg = function(attr){
    var url = location.href;
    var reg = new RegExp(attr+'=([^&]+)');
    var match = url.match(reg);
    return match?match[1]:null;
}
//初始填入防伪码
inputfwcode = function(fwcode){
    $('input[name=fwcode]').val(fwcode)
}
init = function(){
    var fwcode = getarg('fwcode');
    if(fwcode) inputfwcode(fwcode);
}
init();
//调用微信扫码
var bugfix = false;
$(document).on('click', '#fwscan:not(.weui_btn_disabled)', function(){
    bugfix = true;
    wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: fwscansucfunc
    });
})
fwscansucfunc = function(res){
    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
    var codes = result.split('http://wap.xologood-fc.com/yingbaozhineng/fw.html?code=')
    if(codes.length!=2){
        mymessage('二维码有误')
    }else{
        var code = codes[1]
        $('input[name=fwcode]').val(code)
    }    
}